package org.example.xsda.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis 缓存服务
 */
@Slf4j
@Service
public class RedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 设置缓存（默认过期时间30分钟）
     */
    public void set(String key, Object value) {
        set(key, value, 30, TimeUnit.MINUTES);
    }

    /**
     * 设置缓存（自定义过期时间）
     */
    public void set(String key, Object value, long timeout, TimeUnit unit) {
        try {
            redisTemplate.opsForValue().set(key, value, timeout, unit);
            log.debug("设置缓存成功：key={}, timeout={} {}", key, timeout, unit);
        } catch (Exception e) {
            log.error("设置缓存失败：key={}", key, e);
        }
    }

    /**
     * 获取缓存
     */
    public Object get(String key) {
        try {
            Object value = redisTemplate.opsForValue().get(key);
            if (value != null) {
                log.debug("从缓存获取数据成功：key={}", key);
            } else {
                log.debug("缓存中不存在：key={}", key);
            }
            return value;
        } catch (Exception e) {
            log.error("获取缓存失败：key={}", key, e);
            return null;
        }
    }

    /**
     * 删除缓存
     */
    public void delete(String key) {
        try {
            redisTemplate.delete(key);
            log.debug("删除缓存成功：key={}", key);
        } catch (Exception e) {
            log.error("删除缓存失败：key={}", key, e);
        }
    }

    /**
     * 批量删除缓存
     */
    public void delete(String... keys) {
        try {
            redisTemplate.delete(Arrays.asList(keys));
            log.debug("批量删除缓存成功：keys={}", Arrays.toString(keys));
        } catch (Exception e) {
            log.error("批量删除缓存失败：keys={}", Arrays.toString(keys), e);
        }
    }

    /**
     * 根据前缀删除缓存
     */
    public void deleteByPattern(String pattern) {
        try {
            Set<String> keys = redisTemplate.keys(pattern + "*");
            if (keys != null && !keys.isEmpty()) {
                redisTemplate.delete(keys);
                log.debug("根据前缀删除缓存成功：pattern={}, count={}", pattern, keys.size());
            }
        } catch (Exception e) {
            log.error("根据前缀删除缓存失败：pattern={}", pattern, e);
        }
    }

    /**
     * 判断缓存是否存在
     */
    public boolean hasKey(String key) {
        try {
            Boolean result = redisTemplate.hasKey(key);
            return result != null && result;
        } catch (Exception e) {
            log.error("判断缓存是否存在失败：key={}", key, e);
            return false;
        }
    }

    /**
     * 设置过期时间
     */
    public void expire(String key, long timeout, TimeUnit unit) {
        try {
            redisTemplate.expire(key, timeout, unit);
            log.debug("设置过期时间成功：key={}, timeout={} {}", key, timeout, unit);
        } catch (Exception e) {
            log.error("设置过期时间失败：key={}", key, e);
        }
    }

    /**
     * 获取过期时间
     */
    public Long getExpire(String key) {
        try {
            return redisTemplate.getExpire(key, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("获取过期时间失败：key={}", key, e);
            return null;
        }
    }

    /**
     * List操作：右推
     */
    public void listPush(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            log.debug("List右推成功：key={}", key);
        } catch (Exception e) {
            log.error("List右推失败：key={}", key, e);
        }
    }

    /**
     * List操作：获取范围内的元素
     */
    public List<Object> listRange(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            log.error("List获取范围失败：key={}", key, e);
            return null;
        }
    }

    /**
     * Hash操作：设置值
     */
    public void hashPut(String key, String hashKey, Object value) {
        try {
            redisTemplate.opsForHash().put(key, hashKey, value);
            log.debug("Hash设置值成功：key={}, hashKey={}", key, hashKey);
        } catch (Exception e) {
            log.error("Hash设置值失败：key={}, hashKey={}", key, hashKey, e);
        }
    }

    /**
     * Hash操作：获取值
     */
    public Object hashGet(String key, String hashKey) {
        try {
            return redisTemplate.opsForHash().get(key, hashKey);
        } catch (Exception e) {
            log.error("Hash获取值失败：key={}, hashKey={}", key, hashKey, e);
            return null;
        }
    }

    /**
     * Hash操作：删除值
     */
    public void hashDelete(String key, Object... hashKeys) {
        try {
            redisTemplate.opsForHash().delete(key, hashKeys);
            log.debug("Hash删除值成功：key={}", key);
        } catch (Exception e) {
            log.error("Hash删除值失败：key={}", key, e);
        }
    }
}

